package com.huluobo.apps.pages

import android.os.Environment
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.apps.AppsIntent
import com.huluobo.apps.AppsViewModel
import com.huluobo.apps.entity.AppsEntity
import com.huluobo.apps.entity.AppsEntityItem
import com.huluobo.lib_base.BaseApp
import com.huluobo.lib_base.BaseLoadingDialog
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_base.StateType
import com.huluobo.lib_base.UIState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

/**
 *  Created by LC on 2025/7/23.
 */

@Composable
fun AppsPage(navHostController: NavHostController, vm: AppsViewModel = hiltViewModel()) {
    //compost中页面数据源的类型,类似观察者的数据源,可以根据内容的改变刷新页面
    val list = remember {
        SnapshotStateList<AppsEntityItem>()
    }

    //控制是否弹出进度条
    var isShowProgress by remember {
        mutableStateOf(false)
    }

    //控制是否弹出安装的进度条
    var isShowLaunch by remember {
        mutableStateOf(false)
    }

    //安装的进度,0-1 的float值
    var currentProgress by remember {
        mutableStateOf(0f)
    }

    //控制更新进度的协程
    var scope = rememberCoroutineScope()

    //LaunchedEffect 开启page中协程的部分,key1传递空可以在页面初始化的时候调用
    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                Log.e("TagA", "页面状态接收:${it.toString()}")
                when (it) {
                    is UIState.OnFailed -> {
                        isShowProgress = false
                        ToastUtils.showLong("获取应用程序列表失败:${it.msg}")
                        Log.e("TagA", " 获取应用程序列表失败:${it.msg}")
                    }

                    UIState.OnLoading -> {
                        isShowProgress = true
                    }
                    //*代表所有类型,当页面有多个网络请求的时候,都走的状态的成功,所以不能固定类型
                    is UIState.OnSuccess<*> -> {
                        Log.e("TagA", "data:${it.data.toString()}")
                        isShowProgress = false
                        if (it.type == StateType.DEFAULT) {
                            list.clear()
                            list.addAll(it.data as AppsEntity)
                        }

                        if (it.type == StateType.DOWNLOAD) {
                            ToastUtils.showLong(it.data.toString())
                        }
                    }
                }
            }
        }
        //初始化的时候发送请求数据源的意图
        vm.sendIntent(AppsIntent.GetApps)
    })

    if (isShowProgress) {
        BaseLoadingDialog()
    }

    Column(Modifier.padding(10.dp)) {
        BaseTitle(title = "在线应用", navHostController = navHostController)
        Spacer(modifier = Modifier.height(10.dp))
        LazyVerticalGrid(columns = GridCells.Fixed(2), content = {
            items(list) {
                AppsItem(appsEntityItem = it, vm) {
                    isShowLaunch = true
                    scope.launch {
                        for (i in 1..100) {
                            currentProgress = i.toFloat() / 100
                            //每次更新进度的时候,延时0.1秒
                            delay(100)
                        }
                        isShowLaunch = false
                        ToastUtils.showLong("安装成功")
                    }
                }
            }
        }, verticalArrangement = Arrangement.spacedBy(20.dp), horizontalArrangement = Arrangement.spacedBy(20.dp))
    }

    if (isShowLaunch) {
        AlertDialog(onDismissRequest = {}, confirmButton = {}, text = {
            Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
                LinearProgressIndicator(progress = currentProgress)
                Text(text = "${(currentProgress * 100).toInt()}/100")
            }
        }, title = {
            Text(text = "安装中...")
        })
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun AppsItem(appsEntityItem: AppsEntityItem, vm: AppsViewModel, longClick: () -> Unit) {

    //获取系统文件夹
//    val file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)

    //通过app的context拿到app的文件路径,如果没有,会自动创建一个
    val file = BaseApp.context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)

    //控制下载的弹窗
    var isShow by remember {
        mutableStateOf(false)
    }

    Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.combinedClickable(
        onClick = {
            isShow = true
        },
        onLongClick = {
            longClick()
        }
    )) {
        AsyncImage(
            model = appsEntityItem.appIcon,
            contentDescription = "",
            modifier = Modifier
                .fillMaxWidth()
                .size(80.dp),
            alignment = Alignment.Center
        )
        Text(text = "名称 : ${appsEntityItem.appName}", fontWeight = FontWeight.Bold)
        Text(text = "网址 : ${appsEntityItem.netUrl}", maxLines = 1, overflow = TextOverflow.Ellipsis)
        Text(text = "创建时间 : ${appsEntityItem.createTime}", color = Color.LightGray, fontSize = 13.sp)
        Text(text = "更新时间 : ${appsEntityItem.updateTime}", color = Color.LightGray, fontSize = 13.sp)
    }

    if (isShow) {
        AlertDialog(onDismissRequest = {
            isShow = false
        }, confirmButton = {
            TextButton(onClick = {
                //发送下载的意图
                vm.sendIntent(
                    AppsIntent.DownloadApk(
                        appsEntityItem.apkUrl,
                        File(file, appsEntityItem.appName + ".apk")
                    )
                )
                isShow = false
            }) {
                Text(text = "确认")
            }
        }, dismissButton = {
            TextButton(onClick = {
                isShow = false
            }) {
                Text(text = "取消")
            }
        }, title = {
            Text(text = "下载提醒")
        }, text = {
            Text(text = "是否要下载${appsEntityItem.appName}吗?")
        })
    }
}